﻿<style>
.tabBox {
  padding-top: 20px;
}

.tabBox.el-tabs--left {
  height: auto !important;
}

.tabBox .el-tabs__header .is-left .el-tabs__item {
  width: 60px;
  line-height: 24px;
  height: auto;
  word-wrap: break-word;
  white-space: pre-line;
  /*margin-bottom: 20px;*/
  padding-bottom: 20px;
}


  .invoke-result .el-tabs--border-card>.el-tabs__content {
    padding: 5px;
  }

  .invoke-result .el-tabs__item {
    height: 30px;
    line-height: 30px;
  }

 .invoke-result .el-tabs__nav-next,
  .invoke-result .el-tabs__nav-prev {
    line-height: 30px;
  }

  #data-tab .el-tabs__header.is-top {
    margin: 0;
  }

  #data-tab .el-input-group__append,
  .el-input-group__prepend {
    padding: 0 10px;
  }

  #data-tab .el-input__inner {
    padding: 0 8px;
  }

  .montecarlo .el-form-item {
    margin-bottom: 5px;
  }

  .montecarlo .block {
    border: 1px solid #DCDFE6;
    margin-top: 10px;
    padding: 10px;
    box-sizing: border-box;
    position: relative;
    border-radius: 4px;
  }

  .montecarlo .block-title {
    left: 10px;
    top: -15px;
    background-color: white;
    padding: 5px;
    color: gray;
    position: absolute;
  }

  .mini-input .el-input__inner {
    padding: 0 8px;
  }

  .mini-input .el-button+.el-button {
    margin-left: 5px;
  }

  .mini-input .el-button--small,
  .mini-input .el-button--small.is-round {
    padding: 9px 12px;
  }

  .option-container .el-col {
    height: 40px;
  }
</style>
<template>
  <div style="height: 100%;position: relative;padding:0 10px 0px 10px;box-sizing: border-box;"
    ref="project_invoke_container" v-loading="isLoading" :element-loading-text="loadingText">
    <el-row class="option-container">
      <el-form label-width="100px" size="small" style="width:100%">
        <el-col span="8">
          <el-form-item label="项目名称:">
            <el-input readonly v-model="currentProjectName"></el-input>
          </el-form-item>
        </el-col>
        <el-col span="8">
          <el-form-item label="评价名称:">
<!--            <el-input readonly v-model="computeVersion.name"></el-input>-->
            <el-select v-if="computeVersionList&&computeVersion&&computeVersion.id&&!isLoading"
                       v-model="computeVersion.id"
                       :ref="computeVersion.id"
                       @change="changeComputeVersion">
              <el-option v-for="item in computeVersionList" :key="item.id" :value="item.id" :label="item.name">
                <span style="float: left" :style="{'padding-left':item.parentId?'20px':'0'}">{{ item.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ markNameMap[item.mark] }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col span="8">
          <el-form-item label="评价模型:">
            <data-select disabled data-url="/settings/model/publish/data" v-model="computeVersion.modelId"></data-select>
<!--            <el-select v-model="computeVersion.modelId" placeholder="请选择" disabled>-->
<!--              <el-option v-for="item in modelList" :key="item.id" :label="item.name" :value="item.id">-->
<!--              </el-option>-->
<!--            </el-select>-->
          </el-form-item>
        </el-col>
        <el-col span="8">
          <el-col span="10">
            <el-form-item label="评价期:">
              <el-input v-model="computeVersion.evaluationPeriod" class="mini-input" autocomplete="off" style="width:40px"
                placeholder="请输入内容"></el-input> 年
            </el-form-item>
          </el-col>
          <el-col span="14">
            <el-form-item label="" label-width="10px">
              开始年
              <el-input v-model="computeVersion.calculateYearStart" class="mini-input" readonly autocomplete="off"
                style="width:70px" placeholder="开始年"></el-input>
              结束年
              <el-input v-model="computeVersion.calculateYearEnd" class="mini-input" autocomplete="off"
                style="width:70px" placeholder="结束年" readonly></el-input>
            </el-form-item>
          </el-col>
        </el-col>
        <el-col span="8">

        </el-col>

        <el-col span="8" class="mini-input" style="text-align: right">
          <el-checkbox label="拉齐后对减" v-model="computeVersion.costPull" style="margin-right: 5px;" ></el-checkbox>
          <el-button type="primary" @click="subtract" size="small">对减
          </el-button>
          <el-button v-if="invokeState.state=='complete'&&checkPermission('model:create')"
            @click="downloadLog" size="small">日志下载
          </el-button>

          <el-button v-if="exportPreviewData['result']&&exportPreviewData['result'].sheetList" type="primary" @click="downloadFile"
            size="small">导出
          </el-button>
<!--          <el-button v-if="invokeState.state=='complete'" type="primary" @click="downloadReportFile"-->
<!--                     size="small">报告生成-->
<!--          </el-button>-->
          <el-button
              v-if="invokeState.state=='complete'&&currentProject.state=='audit'&&computeVersion.type=='report'&&checkPermission('evaluation:audit')"
              type="primary" @click="auditVersion(true)" size="small">审核通过
          </el-button>
          <el-button
              v-if="invokeState.state=='complete'&&currentProject.state=='audit'&&computeVersion.type=='report'&&checkPermission('evaluation:audit')"
              type="danger" @click="auditVersion(false)" size="small">退回
          </el-button>

        </el-col>
      </el-form>
    </el-row>

    <div style="position: relative;" class="invoke-result">
<!--      <el-tabs tabPosition="left" class="tabBox" @tab-click="changeTab(activeTab)" v-model="activeTab">-->
<!--        <el-tab-pane label="有项目" name="has_project" :lazy="true">-->
<!--          <excel-view row-selected-color="rgb(151,242,106,0.3)" v-if="exportPreviewData['has_project']&&exportPreviewData['has_project'].sheetList" :data="exportPreviewData['has_project']"-->
<!--                      :max-height="contentMaxHeight"></excel-view>-->
<!--        </el-tab-pane>-->
<!--        <el-tab-pane label="无项目" name="no_project">-->
<!--          <excel-view row-selected-color="rgb(151,242,106,0.3)" v-if="exportPreviewData['no_project']&&exportPreviewData['no_project'].sheetList" :data="exportPreviewData['no_project']"-->
<!--                      :max-height="contentMaxHeight"></excel-view>-->
<!--        </el-tab-pane>-->
<!--        <el-tab-pane label="无项目成本拉齐" name="no_project_cost_pull" :disabled="!exportPreviewData['no_project_cost_pull']">-->
<!--          <excel-view row-selected-color="rgb(151,242,106,0.3)" v-if="exportPreviewData['no_project_cost_pull']&&exportPreviewData['no_project_cost_pull'].sheetList" :data="exportPreviewData['no_project_cost_pull']"-->
<!--                      :max-height="contentMaxHeight"></excel-view>-->
<!--        </el-tab-pane>-->
<!--        <el-tab-pane label="对减结果" name="result" :disabled="!exportPreviewData['result']">-->
          <excel-view row-selected-color="rgb(151,242,106,0.3)" v-if="exportPreviewData['result']&&exportPreviewData['result'].sheetList" :data="exportPreviewData['result']"
                      :max-height="contentMaxHeight" border-color="#ccc"></excel-view>
        <div v-else style="text-align: center;padding: 50px;">
          无对减结果，请点击对减进行计算
        </div>
<!--        </el-tab-pane>-->
<!--      </el-tabs>-->

    </div>

    <el-dialog v-loading="loadingComputeVersion" title="保存评价结果" :visible.sync="detailDlgVisible"
      :close-on-click-modal="false" width="50%">
      <el-form label-width="auto" style="width:100%;margin-top:20px;">
        <el-form-item label="评价名称:">
          <el-input v-model="computeVersion.name" autocomplete="off" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="评价模型:">
          <data-select disabled data-url="/model/pubdata" v-model="computeVersion.modelId"></data-select>
<!--          <el-select disabled v-model="computeVersion.modelId" placeholder="请选择">-->
<!--            <el-option v-for="item in modelList" :key="item.id" :label="item.name" :value="item.id">-->
<!--            </el-option>-->
<!--          </el-select>-->
        </el-form-item>
        <el-row>
          <el-col span="8">
            <el-form-item label="评价期:">
              <el-input readonly v-model="computeVersion.evaluationPeriod" autocomplete="off" placeholder="请输入内容">
                <template slot="append">年</template></el-input>
            </el-form-item>
          </el-col>
          <el-col span="16">
            <el-form-item>
              <el-col span="11">
                <el-input readonly v-model="computeVersion.calculateYearStart" autocomplete="off" placeholder="开始年">
                </el-input>
              </el-col>
              <el-col span="2">~</el-col>

              <el-col span="11">
                <el-input readonly v-model="computeVersion.calculateYearEnd" autocomplete="off" placeholder="结束年">
                </el-input>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="">
            <el-checkbox label="根据经济极限年判断评价期" disabled v-model="computeVersion.cutoff" style="margin-right: 15px">
            </el-checkbox>
          </el-form-item>
        </el-row>
        <el-form-item label="备注:">
          <el-input type="textarea" v-model="computeVersion.remark" autocomplete="off" placeholder="请输入内容"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" @click="copyVersion">保存</el-button>
        <el-button @click="detailDlgVisible = false">取消</el-button>
      </span>
    </el-dialog>

  </div>

</template>

<script>

import DataSelect from "../../components/data-select";
export default {
  name: "ComputeSubtract",
  $$route:{
    meta: {
      title: '评价详情'
    }
  },
  components: {DataSelect},
  data() {
    return {
      computeVersionData:[],
      computeVersionList:null,
      markNameMap:{
        'has_project':'有项目版本',
        'no_project':'无项目版本',
        'no_project_cost_pull':'无项目拉齐版本',
        'result':'对减版本',
      },
      sourceComputeVersion: '',
      detailDlgVisible: false,
      isLoading: false,
      loadingText: '正在处理...',
      formLabelWidth: '120px',
      inputTableList: [],
      inputTableMap: {},
      computeVersion: {
        id: '',
        modelId: '',
        name: '',
        type: '',
        cutOff: false,
        costPull: false,
        buildYearCount: 0,
        calculateYearStart: new Date().getFullYear(),
        calculateYearEnd: new Date().getFullYear() + 15
      },
      currentProject: {
        id: ''
      },
      currentProjectName: '',
      //当前页面状态
      invokeState: {
        //当前状态，默认为录入
        state: 'record',
        //展示标签页，默认展示录入标签页
        display: 'record',
        //录入数据是否发生变更
        recordChanged: false,
      },//当前页面状态
      defaultInvokeState: {
        //当前状态，默认为录入
        state: 'record',
        //展示标签页，默认展示录入标签页
        display: 'record',
        //录入数据是否发生变更
        recordChanged: false,
      },

      exportPreviewData: {},
      activeTab: 'has_project',
    }
  },
  props: {
    pageHeight: {
      type: Number,
      default: 300
    }
  },
  computed: {
    contentMaxHeight: function () {
      return this.pageHeight - 95;
    },


  },
  watch:{
    $route(to,from) {
      // if(this.computeVersion.id!=to.query.version) {
      //   this.init(this.currentProject.id,to.query.version);
      // }
    }
  },
  created: function () {
    // this.loadModelList();
    this.$emit('top-menu', '/project/info-list');
  },
  mounted: function () {
    const projectId = this.$route.query.id;
    const version = this.$route.query.version
    this.loadComputeVersionList(projectId);
    this.sourceComputeVersion = version;
    this.init(projectId,version);
      // this.loadProjectInfo(projectId);
      // if (version && version.length > 0) {
      //   //加载版本信息，加载录入模型
      //   this.loadComputeVersionInfo(version);
      // }
  },

  methods: {
    //初始化
    init(projectId,version){
      this.initInvokeState();
      this.exportPreviewData = {};
      this.sourceComputeVersion = version;
      this.loadProjectInfo(projectId);
      if (version && version.length > 0) {
        //加载版本信息，加载录入模型
        this.loadComputeVersionInfo(version);
      }
    },

    downloadFile: function () {
      window.open(this.$ctx+'/compute_version/result/download?dataVersion=' + this.computeVersion.id);
    },
    // downloadReportFile: function () {
    //   window.open(this.$ctx+'/compute_version/report/download?dataVersion=' + this.computeVersion.id);
    // },
    downloadLog: function () {
      window.open('/compute_version/log/download?dataVersion=' + this.computeVersion.id);
    },
    /**
     * 初始化页面状态
     */
    initInvokeState(state, display, recordChanged) {
      if (!state) {
        state = 'record';
      }
      if (!display) {
        display = 'record';
      }
      this.invokeState = {
        state: state,
        display: display,
        recordChanged: recordChanged ? true : false,
      };
    },
    subtract: function () {
      //修改页面状态为执行计算，展示录入标签
      this.initInvokeState('invoke');
      this.loadingText = '正在计算...';
      this.isLoading = true;
      this.$post("/compute_version/subtract", this.computeVersion, (response) => {
        this.$message({
          message: '计算成功',
          type: 'success'
        });

        if(this.$route.query.src) {
          let currentPath = this.$route.fullPath;
          this.$emit('tab-refresh',this.$route.query.src,null,()=>{
            this.$emit('tab-active',currentPath)
          })

        }
        this.computeVersion.computeTime=1;
        this.loadComputeVersionList(this.currentProject.id)
        this.previewData(this.computeVersion);
      }, (response) => {
        if (response.code != 0) {
          //如果计算失败，则应展示录入参数页面
          this.initInvokeState();
          this.isLoading = false;
        } else {
          this.loadingText = '正在加载数据...';
        }
      });

      // }, (response) => {
      //   if (response.code != 0) {
      //     this.isLoading = false;
      //     this.invokeState = {state: 'record', display: 'record'};
      //   }
      // });
    },

    changeTab: function (tab) {
      if(!this.exportPreviewData[tab]) {
        //如果当前标签页数据未加载，则加载数据
        var version = null;
        //根据mark找到对应的评价版本
        if(this.computeVersion.mark == tab) {
          version = this.computeVersion;
        } else {
          for(var item of this.computeVersion.children) {
            if(item.mark == tab) {
              version = item;
              break;
            }
          }
        }

        this.previewData(version);
      }
    },

    /**
     * 预览结果数据
     */
    previewData: function (version) {
      if(!version.computeTime){
        //如果没有计算时间，则未计算
        return;
      }
      this.loadingText = '正在加载...';
      this.isLoading = true;
      // this.$get("/data/compute/preview?dataVersion=" + version.id, {}, (response) => {
      this.$get("/compute_version/result/preview?dataVersion=" + version.id, {}, (response) => {


        this.exportPreviewData[version.mark] = response.data;
        //初始化页面状态为计算完成，展示结果标签页
        this.initInvokeState('complete', 'result');
        this.isLoading = false;
      }, (response) => {
        if (response.code != 0) {
          this.initInvokeState();
        }
        this.isLoading = false;
      });
    },

    // loadModelList: function () {
    //   this.$get("/model/pubdata", {}, (response) => {
    //     this.modelList = response.data;
    //     var map = {};
    //     for (var i = 0; i < this.modelList.length; i++) {
    //       map[this.modelList[i].id] = this.modelList[i].name;
    //     }
    //     this.modelMap = map;
    //   });
    // },
    openSaveDlg() {
      this.detailDlgVisible = true;
    },
    /**
     * 保存结果
     */
    saveResult() {

      var versionData = JSON.parse(JSON.stringify(this.computeVersion));
      this.$post("/compute_version/save_temp", versionData, (response) => {
        // this.computeVersion.id = response.data;
        this.detailDlgVisible = false;
        this.$message.success('保存成功！');
        this.previewData(this.computeVersion);

      });
    },
    /**
     * 复制版本数据
     */
    copyVersion() {

      this.computeVersion.projectId = this.currentProject.id;
      var versonData = JSON.parse(JSON.stringify(this.computeVersion));
      versonData.type = 'default';
      this.$post("/compute_version/copy", versonData, (response) => {
        // this.computeVersion.id = response.data;
        this.detailDlgVisible = false;
        this.$message.success('保存成功！');
        this.computeVersion.type = 'default';
        this.sourceComputeVersion = this.computeVersion.id;
        history.pushState(null, null, "/#/evaluation/compute-invoke?id=" + this.currentProject.id + "&version=" +
            this.computeVersion.id)

      });
    },
    loadProjectInfo(id) {
      this.$get("/project_info/info/" + id, {}, (response) => {
        this.currentProject = response.data;
        this.currentProjectName = this.currentProject.name;
        this.$emit('add-bread', {
          name: this.currentProject.name
        })
      });
    },

    /**
     * 加载计算版本信息
     * @param versionId 版本id
     * @param hook 获取成功后的回调函数
     */
    loadComputeVersionInfo(versionId, hook) {
      this.isLoading = true;
      this.$get("/compute_version/info/" + versionId, {}, (response) => {
        this.computeVersion = response.data;
        // this.changeTab(this.activeTab);
        if (!this.computeVersion || !this.computeVersion.id) {
          //如果版本不存在，则跳转到版本列表页
          this.openPage('/evaluation/compute-version-list', this.$route.query.id);
          return;
        }
        this.isLoading = false;
        this.previewData(this.computeVersion);
        this.$set(this.computeVersion, 'evaluationPeriod', this.computeVersion.calculateYearEnd - this.computeVersion.calculateYearStart + 1);
        if (hook) {
          hook(response.data)
        }
      },(response)=>{
        if(response.code!=0) {
          this.isLoading = false;
        }
      });
    },
    auditVersion(pass) {
      this.computeVersion.pass = pass;
      this.$post("/compute_version_state/audit", this.computeVersion, (response) => {
        this.$message.success('保存成功！');
        this.init(this.currentProject.id,this.computeVersion.id);
        this.loadProjectInfo(this.currentProject.id);
      });
    },

    //加载评价版本,并将其展开
    loadComputeVersionList(projectId) {
      this.$get("/compute_version/data", {projectId:projectId,pageSize:-1}, (response) => {
        let list = [];
        for (let item of response.data) {
          list.push(item);
          if (item.children && item.children.length > 0) {

            for (let child of item.children) {
              child.name = child.name;
              list.push(child);
            }
          }
        }
        this.computeVersionList = list;
      }, () => {
      });
    },
    //切换评价版本操作
    changeComputeVersion(versionId) {

      let version = null;
      for(let item of this.computeVersionList) {
        if(item.id==versionId) {
          version = item;
        }
      }

      if(!version) {
        console.log("未找到该版本:"+versionId);
        return;
      }
      let oldVersionId=this.$route.query.version;
      let path = this.$route.fullPath;
      if(version.mark=='result') {
        this.isLoading = true;
        history.pushState(null, null, "/#/evaluation/compute-subtract?id=" + version.projectId + "&version=" +
            versionId);
        this.init(version.projectId,versionId);
      } else {
        this.closePage(path);
        this.openPage('/evaluation/compute-invoke',version.projectId,{version:version.id});
        this.computeVersion.id = oldVersionId;

      }
    }

  }


}
</script>